import { Component, OnInit } from '@angular/core';
import { DebounceService } from '../../../@core/utils/debounce';
import { GridTable } from '../../../@core/data/grid-table';
import { GridTableService } from '../../../@core/service/grid-table.service';

@Component({
  selector: 'tables-tree-grid',
  templateUrl: './tree-grid.component.html',
  styleUrls: ['./tree-grid.component.scss']
})
export class TreeGridComponent implements OnInit {

  constructor(
    private gridtableService: GridTableService,
    private debounceService: DebounceService
  ) {}

  ngOnInit(): void {
    this.getGridlists();
  }

  gridList: GridTable[];

  gridModel: GridTable = {
    id: '',
    firstName: '',
    lastName: '',
    userName: '',
    email: '',
    age: '',
    bol: false
  };
  searchModel: GridTable = {
    id: '',
    firstName: '',
    lastName: '',
    userName: '',
    email: '',
    age: ''
  }

  // 定义一个查询方法
  search(item: GridTable): Function {
    return () => {
      this.gridtableService.searchLists(item)
          .subscribe(gridSearch => this.gridList = gridSearch)}
  }

  getGridlists(): void {
    this.gridtableService.getGridlists()
        .subscribe(gridList => this.gridList = gridList)
  }

  add(item: GridTable): void {
    if (item.id && item.firstName && item.lastName && item.userName && item.email && item.age) {
      this.gridtableService.addList(item)
      .subscribe((item) => {
        this.gridList.unshift(item);
        this.gridModel.bol = false;
        this.gridModel.id = '';
        this.gridModel.firstName = '';
        this.gridModel.lastName = '';
        this.gridModel.userName = '';
        this.gridModel.email = '';
        this.gridModel.age = '';
      })
    } else {
      window.alert('Please Complete Information!')
    }
  }

  delete(item: GridTable): void {
    this.gridList = this.gridList.filter(h => h !== item);
    this.gridtableService.deleteList(item).subscribe()
  }

  update(item: GridTable, index: number): void {
    this.gridtableService.updateList(item).subscribe();
    this.gridList[index].bol = true;
  }

  // 防抖查询
  doSearch(item: GridTable) {
    this.debounceService.debounce(this.search(item), 500)
  }

}
